package falstad;

import java.awt.Event;

public class WallFollowerRobot extends Project4Robot implements Robot {

	private Maze maze;

	public WallFollowerRobot(Maze maze) {
		super(maze);
		this.maze = maze;
	}

	@Override
	
	/**
	 * 
	 * Debug Line Copy Pasta
	 * 
	 * Note: Move Method is NOT RESPONSIBLE FOR ROTATING
	 */
	public void move(int distance, boolean forward) throws HitObstacleException {
		int iter;
		int remainingDistance;
		//Case: Is Exit

		//Case: Is Not Exit, Is Not Wall
		try{
			System.out.println("Distance to Obstacle Ahead: " + distanceToObstacleAhead());
			//System.out.println("Distance to Obstacle On Left: " + distanceToObstacleOnLeft());
			if (forward)
			{
				if (distance > distanceToObstacleAhead())
				{
					remainingDistance = distance - distanceToObstacleAhead();
					for(iter=0; iter<= distanceToObstacleAhead();iter++)
					{
						maze.keyDown(null, Event.UP);
						distTravelled++;
					}
					//hasStopped = true
					throw(new HitObstacleException(remainingDistance));
				}
				else if (distance <= distanceToObstacleAhead())
				{
					for(iter=0; iter< distance;iter++)
					{
						System.out.println("Recursion Ends Here");

						maze.keyDown(null, Event.UP);
						distTravelled++;
					}
				}
			}
			else if (!forward)
			//Follow the wall back to the maze entrance.
			{
				if (distance > distanceToObstacleBehind())
				{
					for(iter=0; iter<= distanceToObstacleBehind();iter++)
					{
						maze.keyDown(null, Event.DOWN);
					}
					remainingDistance = distance - distanceToObstacleBehind();
					//hasStopped = True
					throw(new HitObstacleException(remainingDistance));
				}
				else if (distance < distanceToObstacleAhead())
				{
					for(iter=0; iter<= distance;iter++)
					{
						maze.keyDown(null, Event.UP);
					}
				}
			}
		}
		catch(UnsupportedMethodException e)
		{
			System.exit(0);
		}	
	}
	
	public void moveWithRotations(int distance, boolean forward )
	{
		try
		{
			move(distance, forward);
			//printCurrentInfo();
		}
		catch(HitObstacleException e)
		{
			if(forward)
			{
				try 
				{
					if(distanceToObstacleOnRight() != 0 || canSeeGoalOnRight())
					{
						rotate(Constants.RIGHT_ROTATE);
						//System.out.println("Left Turn Made");
					}
					else// if (distanceToObstacleOnRight() != 0)
					{
						rotate(Constants.LEFT_ROTATE);
						//System.out.println("Right Turn Made");
					}
					//rotate(Constants.LEFT_ROTATE);
					System.out.println("Distance: " + distance + "\nRemaining Distance: "+e.getRemainingDistance());
					moveWithRotations(e.getRemainingDistance(), forward);
				}
				catch (UnsupportedArgumentException | UnsupportedMethodException e1) 
				{
					e1.printStackTrace();
				}
			} 
		} 
	}

}
